package com.q.tqb.activity.mine;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.q.tqb.R;
import com.q.tqb.base.AppConst;
import com.q.tqb.base.BaseActivity;
import com.q.tqb.model.BalanceInfo;
import com.q.tqb.model.BaseInfo;
import com.q.tqb.model.WxPayData;
import com.q.tqb.util.LogUtil;
import com.q.tqb.util.MD5Util;
import com.q.tqb.util.SPUtil;
import com.q.tqb.util.StringUtil;
import com.q.tqb.util.http.IResponse;
import com.q.tqb.util.http.IResponse2;
import com.q.tqb.util.http.OkHttpUtil;
import com.q.tqb.view.dialog.PayDialog;
import com.q.tqb.view.dialog.PayPassDialog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MineTweeterIntroActivity extends BaseActivity {


    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.tv_add_tweeter)
    TextView tvAddTweeter;
    private int uid;
    private String orderId;
    private PayDialog payDialog;
    private MyBroadcastReceiver mBroadcastReceiver;
    private int payType;
    private String payPass;
    private String myMoney;

    @Override
    public int getLayoutId() {
        return R.layout.activity_mine_tweeter_intro;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        setTitle("入驻社区");
        uid = (int) SPUtil.get(this, "uid", 0);
        initReceiver();
        getMoney();
    }


    @OnClick({R.id.iv_back, R.id.tv_add_tweeter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_add_tweeter:
//                addTweeter();
                addCommunity();
                break;
            default:
                break;
        }
    }

    private void initReceiver() {
        mBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConst.PAY_TWEETER);
        registerReceiver(mBroadcastReceiver, intentFilter);
    }

    private void addCommunity(){
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));

        mProgressDialog.show();
        OkHttpUtil.getInstance().post2(this, AppConst.URL_ADD_COMMUNITY, map, new IResponse2() {

            @Override
            public void onSuccess(JsonElement element, String msg) {
                showToast(msg);
                mProgressDialog.dismiss();
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
                mProgressDialog.dismiss();
            }
        });
    }



    private void addTweeter() {
        payDialog = new PayDialog(MineTweeterIntroActivity.this, 88, myMoney);

        payDialog.setOnSettingListener(new PayDialog.CommonListener() {
            @Override
            public void onClick(int type) {
                if (type == 1) {
                    payType = 3;
                    PayPassDialog payPassDialog = new PayPassDialog(MineTweeterIntroActivity.this, 88, 1);
                    payPassDialog.show();
                    showInputMethod();
                    payPassDialog.setOnSettingListener(new PayPassDialog.CommonListener() {
                        @Override
                        public void onClick(String pass) {
                            payPass = pass;
                            payOrder();
                        }
                    });
                } else {
                    payType = 2;
                    payOrder();
                }

            }
        });
        payDialog.show();

    }


    private void getMoney() {

        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));
        OkHttpUtil.getInstance().post(this, AppConst.URL_GET_MONEY, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                BalanceInfo balanceInfo = gson.fromJson(result, BalanceInfo.class);
                myMoney = balanceInfo.getBalance();

                SPUtil.put(MineTweeterIntroActivity.this, "withdraw", myMoney);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                myMoney = SPUtil.getString(MineTweeterIntroActivity.this, "withdraw");
            }
        });
    }

    private void payOrder() {

        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("pay_type", payType + "");
        if (payType == 3) {
            map.put("pay_password", payPass);
        }
       // 17232

        map.put("token", StringUtil.getToken(uid));
        mProgressDialog.show();
        LogUtil.i(map.toString());
        OkHttpUtil.getInstance().post(this, AppConst.URL_ADD_USER_AGENT, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                mProgressDialog.dismiss();
                try {
                    AppConst.ORDER_TYPE = 4;
                    JSONObject jsonObject = new JSONObject(element.toString());
                    orderId = jsonObject.getString("order_id");
                    if (payType == 2) {
                        wxPay();
                    } else if (payType == 3) {
                        showToast(getString(R.string.mine_tweeter_success));
                        SPUtil.put(MineTweeterIntroActivity.this, "isUserAgent", 1);
                        MineTweeterIntroActivity.this.setResult(RESULT_OK);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                showToast(errorMsg);
                mProgressDialog.dismiss();
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    private void showInputMethod() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 100);
    }

    private void wxPay() {
        Map<String, String> map = new HashMap<>();
        map.put("order_id", orderId);
        mProgressDialog.show();
        OkHttpUtil.getInstance().post(this, AppConst.URL_WX_PAY, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                mProgressDialog.dismiss();
                Gson gson = new Gson();
                WxPayData wxPayData = gson.fromJson(element, WxPayData.class);
                IWXAPI api = WXAPIFactory.createWXAPI(MineTweeterIntroActivity.this, AppConst.WEIXIN_APP_ID);
                api.registerApp(AppConst.WEIXIN_APP_ID);
                PayReq payReq = new PayReq();
                payReq.appId = AppConst.WEIXIN_APP_ID;
                payReq.partnerId = wxPayData.getPartnerid();
                payReq.prepayId = wxPayData.getPrepayid();
                payReq.packageValue = "Sign=WXPay";
                payReq.nonceStr = wxPayData.getNoncestr();
                payReq.timeStamp = "" + wxPayData.getTimestamp();
                payReq.sign = wxPayData.getSign();
                api.sendReq(payReq);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
                mProgressDialog.dismiss();
            }
        });
    }

    class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            showToast(getString(R.string.mine_tweeter_success));
            SPUtil.put(MineTweeterIntroActivity.this, "isUserAgent", 1);
            MineTweeterIntroActivity.this.setResult(RESULT_OK);
            finish();

        }
    }
}
